/**
 * @(#) WorkMediator.as
 *
 * @date		2009. 02. 25.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	근무 - Mediator
 * 				근무관리 Presentation Logic을 관리 
 */
package com.skt.common_hr.teamworktime.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.calendar.DailyItem;
	import com.skt.common_hr.common.calendar.Holiday;
	import com.skt.common_hr.common.puremvc.OverViewMediator;
	import com.skt.common_hr.teamworktime.TeamWorkTimeFacade;
	import com.skt.common_hr.teamworktime.events.SelMemberEvent;
	import com.skt.common_hr.teamworktime.events.SelOrgEvent;
	import com.skt.common_hr.teamworktime.events.WorkTimeEvent;
	import com.skt.common_hr.teamworktime.model.CalendarProxy;
	import com.skt.common_hr.teamworktime.model.MemberSearchProxy;
	import com.skt.common_hr.teamworktime.model.OrgProxy;
	import com.skt.common_hr.teamworktime.model.VacationCodeProxy;
	import com.skt.common_hr.teamworktime.model.vo.DateVO;
	import com.skt.common_hr.teamworktime.model.vo.MemberVO;
	import com.skt.common_hr.teamworktime.model.vo.VacationVO;
	import com.skt.common_hr.teamworktime.view.components.DeleteWorkTimeView;
	import com.skt.common_hr.teamworktime.view.components.ReqForOthersView;
	import com.skt.common_hr.teamworktime.view.components.TeamWorkTimeOverView;
	import com.skt.common_hr.work_sac.WorkFacade;
	import com.skt.common_hr.work_sac.model.TeamVacationProxy;
	import com.skt.common_hr.work_sac.model.VacationQuotaProxy;
	import com.skt.common_hr.work_sac.model.vo.TeamVacationVO;
	import com.wcl.utils.DateUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.core.IFlexDisplayObject;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	

	public class TeamWorkTimeMediator extends OverViewMediator
	{
		public static const NAME:String = "TeamWorkTimeMediator"; 
		
		private var selectedMember:MemberVO;
		private var currentMonth:Date = new Date();

		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function TeamWorkTimeMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		override protected function initializeView():void
 		{
 			preloadData();
 			checkAuthority(Variables.authorities);
 			super.initializeView();
 		}
 		
 		override protected function activatedView():void
 		{
 			setEventListeners();
 			loadTeamMember(Variables.myOrgCode);
 			view.currentCalendarDate = DateUtil.todayNoTime();
 			
 			view.txtOrg.text = Variables.myOrg;
 			view.txtOrg.data = Variables.myOrgCode;
 		}
 		
 		override protected function closedView():void
 		{
 			removeEventListeners();
 		}
 		
 		private function setEventListeners():void
 		{
 			view.addEventListener(TeamWorkTimeOverView.STARTUP_REQ_FOR_OTHERS, onReqForOthers);
 			view.addEventListener(SelMemberEvent.SELECTED_MEMBER, onSelectedMember);
 			view.addEventListener(WorkTimeEvent.CHANGED_MONTH, onChangedMonth);		// Calendar에서 월이 변경되어 있을때
 			view.addEventListener(SelOrgEvent.SELECTED_ORG, onSelectedOrg);
 			view.addEventListener(WorkTimeEvent.DELETE_WORKTIME, onDeleteWorkTime);
 			view.addEventListener(WorkTimeEvent.DELETE_WORKTIME, onDeleteWorkTime);
 		}
 		
 		private function removeEventListeners():void
 		{
 			view.removeEventListener(TeamWorkTimeOverView.STARTUP_REQ_FOR_OTHERS, onReqForOthers);
 			view.removeEventListener(SelMemberEvent.SELECTED_MEMBER, onSelectedMember);
 			view.removeEventListener(WorkTimeEvent.CHANGED_MONTH, onChangedMonth);		// Calendar에서 월이 변경되어 있을때
 			view.removeEventListener(SelOrgEvent.SELECTED_ORG, onSelectedOrg);
 			view.removeEventListener(WorkTimeEvent.DELETE_WORKTIME, onDeleteWorkTime);
 			view.removeEventListener(WorkTimeEvent.DELETE_WORKTIME, onDeleteWorkTime);
 		}
 		
		private function preloadData():void
 		{
 			var orgProxy:OrgProxy = facade.retrieveProxy(OrgProxy.NAME) as OrgProxy;
 			orgProxy.load(Variables.myPernr, "X");
 			
			// 휴가 종류 코드를 로드한다.
  			var codeProxy:VacationCodeProxy = facade.retrieveProxy(VacationCodeProxy.NAME) as VacationCodeProxy;
 			codeProxy.load(Variables.myPernr);
 		}
 		
 		
 		private function checkAuthority(authList:ArrayCollection):void
 		{
 			for each(var vo:* in authList)
 			{
 				if(vo.EMENU == "ALTERREQWORK") {
 					view.registable = true;
 					return;
 				}
 			}
 			view.registable = false;
 		}
 		
 		private function loadTeamMember(code:String):void
 		{
 			var proxy:MemberSearchProxy = facade.retrieveProxy(MemberSearchProxy.NAME) as MemberSearchProxy;
 			proxy.load(code, "");
 		}
 		
 		private function loadCalendarData(pernr:String, month:Date):void
 		{
 			var targetMonth:String = DateUtil.toYYYYMMString(month);
 			var dateProxy:CalendarProxy = facade.retrieveProxy(CalendarProxy.NAME) as CalendarProxy;
 			dateProxy.load(pernr, targetMonth);
 		}

		//2011.12.23 추가
		private function loadTeamVacation(month:String):void
 		{
  			var teamVacationProxy:TeamVacationProxy = facade.retrieveProxy(TeamVacationProxy.NAME) as TeamVacationProxy;
 			teamVacationProxy.load((selectedMember!=null) ? selectedMember.PERNR:null, month);
		} 

		//2011.12.23 추가
 		private function loadVacationQuota():void
 		{
 			var quotaProxy:VacationQuotaProxy = facade.retrieveProxy(VacationQuotaProxy.NAME) as VacationQuotaProxy;
 			quotaProxy.load((selectedMember!=null) ? selectedMember.PERNR:null, DateUtil.thisYear().toString());
 		}
		
 		private function onSelectedOrg(event:SelOrgEvent):void
 		{
			loadTeamMember(event.orgCode); 			
 		}
 		
  		private function onChangedMonth(event:WorkTimeEvent):void
 		{
  			currentMonth = new Date(event.beginDate);
 			loadCalendarData((selectedMember!=null) ? selectedMember.PERNR:null, currentMonth);
 			
 			//2011.12.23
 			var targetMonth:String = DateUtil.toYYYYMMString(currentMonth);//event.beginDate.fullYear.toString() + ((event.beginDate.month+1<10)?"0":"") + (event.beginDate.month+1).toString();
 			loadTeamVacation(targetMonth);	
 		}
 		
 		
 		private function onSelectedMember(event:SelMemberEvent):void
 		{
			 selectedMember = event.member;
			 loadCalendarData(selectedMember.PERNR, currentMonth);
			 
			//2011.12.23
 			var targetMonth:String = DateUtil.toYYYYMMString(currentMonth);//event.beginDate.fullYear.toString() + ((event.beginDate.month+1<10)?"0":"") + (event.beginDate.month+1).toString();
 			loadTeamVacation(targetMonth);				  								
			loadVacationQuota();	
 		}
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return basicInterestMessages.concat( [
					TeamWorkTimeFacade.LOAD_NAMESEARCH_COMPLETE,
					TeamWorkTimeFacade.LOAD_NAMESEARCH_FAILED,
					TeamWorkTimeFacade.LOAD_CALENDAR_COMPLETE,
					TeamWorkTimeFacade.LOAD_CALENDAR_FAILED,
					TeamWorkTimeFacade.LOAD_ORGLIST_COMPLETE,
					TeamWorkTimeFacade.LOAD_ORGLIST_FAILED,
					TeamWorkTimeFacade.INSERT_REQ_VACATION_COMPLETE,
					TeamWorkTimeFacade.INSERT_REQ_WORKTIME_COMPLETE,
					DeleteWorkTimeMediator.DELETED_WORKTIME,
					
					WorkFacade.LOAD_TEAMVACATION_COMPLETE,
					WorkFacade.LOAD_VACATION_QUOTA_COMPLETE
					]);
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			super.handleNotification(note);
			switch(note.getName()) 
			{
				// 2011.1223 아래 두개 추가 
				case WorkFacade.LOAD_TEAMVACATION_COMPLETE:
					view.teamVacationList = getTeamList((note.getBody() as TeamVacationProxy));
					break;
				case WorkFacade.LOAD_VACATION_QUOTA_COMPLETE: 
					view.quotaList = (note.getBody() as VacationQuotaProxy).quotaList;
					break;
							
									
				case TeamWorkTimeFacade.LOAD_NAMESEARCH_COMPLETE:
					view.memberList = (note.getBody() as MemberSearchProxy).memberList;
					commonFacade.setStatusMessage("STATUS_SELECT_MEMBER"); 
					break;
				case TeamWorkTimeFacade.LOAD_CALENDAR_COMPLETE:
					//view.btnInput.enabled = true;
					setCalendar(note.getBody() as CalendarProxy);
					setOTList(note.getBody() as CalendarProxy);
					break;
				case TeamWorkTimeFacade.LOAD_CALENDAR_FAILED:
					break;
				case TeamWorkTimeFacade.LOAD_ORGLIST_COMPLETE:
					view.orgList = (note.getBody() as OrgProxy).orgList;
					break;
				case TeamWorkTimeFacade.LOAD_ORGLIST_FAILED:
					break;
				case TeamWorkTimeFacade.INSERT_REQ_VACATION_COMPLETE:
				case TeamWorkTimeFacade.INSERT_REQ_WORKTIME_COMPLETE:
				case DeleteWorkTimeMediator.DELETED_WORKTIME:
					loadCalendarData(selectedMember.PERNR, currentMonth);
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
		
		
		

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		// 본인 기록은 제외
		private function getTeamList(proxy:TeamVacationProxy):ArrayCollection
		{
			var arr:ArrayCollection = new ArrayCollection();
			for each(var vo:TeamVacationVO in proxy.teamVacationList) {
				trace(Variables.myPernr);
				if(vo.PERNR!=Variables.myPernr) {
					arr.addItem(vo);
				}
			}
			return arr;
		}
				
		private function clearVacationList():void
		{
			view.vacationList = new ArrayCollection();
		}
		
		private function setCalendar(proxy:CalendarProxy):void
		{
			if(selectedMember!=null) {
				view.selectedName 	= selectedMember.ENAME+" ("+selectedMember.PERNR+")";
			}
			view.holidayList 	= toCalendarHoliday(proxy.holidayList);
			view.vacationList 	= toCalendarItems(proxy.vacationList);
			if(selectedMember!=null && view.vacationList.length == 0) {
				commonFacade.setStatusMessage(view.selectedName+"님 해당월 등록된 근태사항이 없습니다.");
			}
			else {
				commonFacade.setStatusMessage(view.selectedName+"님 해당월 등록된 근태사항이 로드 되었습니다.");
			}
		}


		private function setOTList(proxy:CalendarProxy):void
		{
			var otList:ArrayCollection = new ArrayCollection();
			var OT011:Object = new Object();	OT011.gubun = "평일";		OT011.time = 0;
			var OT012:Object = new Object();	OT012.gubun = "평일야간";	OT012.time = 0;
			var OT021:Object = new Object();	OT021.gubun = "휴일";		OT021.time = 0;
			var OT022:Object = new Object();	OT022.gubun = "휴일야간";	OT022.time = 0;
			
			for each(var vo:VacationVO in proxy.vacationList) {
				if(vo.WSTATUS == "2" || vo.WSTATUS == "3") {
					if(vo.AWART == "2010") {
						OT011.time += vo.OT011;
						OT012.time += vo.OT012;
						OT021.time += vo.OT021;
						OT022.time += vo.OT022;
					}
				}
			}
			otList.addItem(OT011);
			otList.addItem(OT012);
			otList.addItem(OT021);
			otList.addItem(OT022);
			view.otList = otList;
		}
				
		private var deleteWorkTimeView:DeleteWorkTimeView = null;
 		private function onDeleteWorkTime(event:WorkTimeEvent):void
 		{
 			//trace("delete worktime = " + event.key);
 			var mediator:DeleteWorkTimeMediator;
 			
 			if(deleteWorkTimeView==null) {
	 			deleteWorkTimeView = PopUpManager.createPopUp(view.root, DeleteWorkTimeView, true) as DeleteWorkTimeView;
	 			PopUpManager.centerPopUp(deleteWorkTimeView);
				mediator = new DeleteWorkTimeMediator(deleteWorkTimeView);
	 			facade.registerMediator(mediator);
	 		}
	 		else {
	 			PopUpManager.addPopUp(deleteWorkTimeView, view.root, true);
	 			mediator = facade.retrieveMediator(DeleteWorkTimeMediator.NAME) as DeleteWorkTimeMediator;
	 		}
	 		deleteWorkTimeView.setFocus();
 			mediator.exec(selectedMember, event.key);
 		}

 		private var reqForm:IFlexDisplayObject = null;
		private function onReqForOthers(event:Event):void
 		{
 			var mediator:ReqForOthersMediator;
 			
 			if(reqForm==null) {
	 			reqForm = PopUpManager.createPopUp(view, ReqForOthersView, true);
	 			PopUpManager.centerPopUp(reqForm);
				mediator = new ReqForOthersMediator(reqForm);
	 			facade.registerMediator(mediator);
	 			mediator.setMember(selectedMember);
	 		}
	 		else {
	 			PopUpManager.addPopUp(reqForm, view, true);
	 			mediator = facade.retrieveMediator(ReqForOthersMediator.NAME) as ReqForOthersMediator;
	 			mediator.setMember(selectedMember);
	 		}
	 		(reqForm as ReqForOthersView).setFocus();
 		}
 		


		private function toCalendarHoliday(src:ArrayCollection):ArrayCollection
		{
			var coll:ArrayCollection = new ArrayCollection();
			for each(var rec:DateVO in src) {
				var vo:Holiday = new Holiday();
				vo.DATUM = new Date(rec.DATUM);
				vo.DTYPE = rec.DTYPE;
				vo.DTEXT = rec.DTEXT;
				coll.addItem(vo);
			}
			return coll;
		}
		
		private var buttonStyleList:Array = ["btn02Return04", "btn02barYellow", "btn02barBlue", "btn02barPink", "btn02barGreen", ""];
		private function toCalendarItems(src:ArrayCollection):ArrayCollection
		{
			var coll:ArrayCollection = new ArrayCollection();
			for each(var rec:VacationVO in src) {
				var vo:DailyItem = new DailyItem();
				vo.WGBN				= rec.WGBN;
				vo.WGBNT			= rec.WGBNT;
				vo.DGBN				= rec.DGBN;
				vo.DGBNT			= rec.DGBNT;
				vo.AWART			= rec.AWART;
				vo.AWATX			= rec.AWATX;
				vo.BEGDA			= new Date(rec.BEGDA);
				vo.ENDDA			= new Date(rec.ENDDA);
				vo.BEGUZ			= new Date(rec.BEGUZ);
				vo.ENDUZ			= new Date(rec.ENDUZ);
				vo.WSTATUS			= rec.WSTATUS;
				vo.WSTATX			= rec.WSTATX;
				vo.TABNR			= rec.TABNR;
				vo.GUBUN			= rec.GUBUN;
				vo.TEXT1			= rec.TEXT1;
				vo.GWAREKEY			= rec.GWAREKEY;
				vo.label = vo.AWATX;
				vo.tootip = vo.TEXT1;
				vo.style = (vo.WSTATUS=="4") ? buttonStyleList[0] : buttonStyleList[parseInt(vo.DGBN)];
					if(vo.WSTATUS!="3") {	
						vo.clickable = false;
						vo.GWAREKEY = "";
					}
					else {
						/*
						if((vo.DGBN=="2" || vo.DGBN=="1") && deletableDay(vo.BEGDA)) {
							vo.clickable = true;
							vo.tootip = "클릭하시면 삭제할 수 있습니다.";
						}
						else {
							vo.clickable = false;
							vo.GWAREKEY = "";
						}
						*/
						vo.clickable = false;
						vo.GWAREKEY = "";
					}
				coll.addItem(vo);
			}
			return coll;
		}
		
		private function deletableDay(date:Date):Boolean
		{
			var today:Date = DateUtil.todayNoTime();
			today.date = 1;
			today.date--;
			today.date = 1;
			return (date > today) ? true : false; 
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():TeamWorkTimeOverView
        {
            return viewComponent as TeamWorkTimeOverView;
        }
	}
}